package com.esd.device.task;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.esd.common.utils.SpringUtils;
import com.esd.device.entity.EsdLog;
import com.esd.device.mapper.EsdLogMapper;
import com.esd.device.service.MailService;
import com.esd.device.utils.YmlConfig;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.time.LocalDateTime;
import java.util.List;

public class EmailJod extends QuartzJobBean {

    private final static EsdLogMapper esdLogMapper = SpringUtils.getBean(EsdLogMapper.class) ;

    private final static YmlConfig ymlConfig = SpringUtils.getBean(YmlConfig.class) ;

    private final static MailService mailService = SpringUtils.getBean(MailService.class) ;

    private final static TemplateEngine templateEngine = SpringUtils.getBean(TemplateEngine.class) ;

    @Override
    protected void executeInternal(JobExecutionContext cxt) throws JobExecutionException {
        if (ymlConfig.getEmailOn()){
            Context context = new Context();
            LocalDateTime now = LocalDateTime.now();
            LocalDateTime time = now.minusMinutes(30);
            LambdaQueryWrapper<EsdLog> queryWrapper = new LambdaQueryWrapper<>() ;
            queryWrapper.lt(EsdLog::getStartTime , time) ;
            queryWrapper.isNull(EsdLog::getEndTime) ;
            queryWrapper.eq(EsdLog::getStatus , "异常") ;
            List<EsdLog> esdLogs = esdLogMapper.selectList(queryWrapper);
            if (esdLogs.isEmpty()){
                return ;
            }
            context.setVariable("list", esdLogs);
            // 获取Thymeleaf 模板
            String emailHTMLContent = templateEngine.process("email/email", context);
            mailService.sendHTMLEmail(
                    ymlConfig.getEmail(),
                    "ESD终端报警邮件提醒",
                    emailHTMLContent);
            EsdLog esdLog = new EsdLog() ;
            esdLog.setEndTime(LocalDateTime.now());
            esdLogMapper.update(esdLog , queryWrapper) ;
        }
    }
}
